<?php
//TODO: 1. Think about using less connections
//2. GetLastMessageID perhaps, can be merged with Refresh
include_once('DbMysql.php');

interface iChat
{
    //Creating chat instance
    public function __construct();
    //Pick an id of last said mesage
    public function GetLastMessageID();
    //add a new reply
    public function NewReply();
    //refresh
    public function Refresh();
}

class Chat
{
    private $database = '';

    //Creating chat instance and setting a connection
    public function __construct()
    {
        $this->database = new DbMysql();
    }

    //Gets a maximun message ID, that now exists
    public function GetLastMessageID()
    {
        $tsql = "SELECT max(ID) as MAX from chat;";
        $this->database->Query($tsql);
        $result = $this->database->Query2Array();
        return $result[1]['MAX'];
    }

    //Adds a new reply to chat table
    public function NewReply($nick, $line)
    {
        $tsql = "INSERT INTO chat (nick, line) values('$nick','$line')";
        $this->database->Query($tsql);
    }

    //returns all chat records, that id is more than curently shown
    public function Refresh($max)
    {
        $codes = array();
        $image = array();
        $i = 0;
        $tsql = "SELECT * FROM smiles";
        $tags = array('[b]','[i]','[u]','[/b]','[/i]','[/u]');
        $ntags = array('<b>','<i>','<u>','</b>','</i>','</u>');
        $this->database->Query($tsql);
        $result = $this->database->Query2Array();
        foreach ($result as $row)
        {
            $codes[$i] = $row['code'];
            $image[$i] = sprintf("<img src='%s'/>" % $row['smile']);
        }
        if ($max)
        {
            $tsql = "SELECT * FROM chat WHERE ID > '$max' ORDER BY ID";
            $this->database->Query($tsql);
            $result = $this->database->Query2Array();
            //header("Content-Type: text/plain; charset=UTF-8");
            foreach ($result as $row)
            {
                //makes a nick into link
                $nick = sprintf('<a onclick = "c.nickLink(\'%s\')" href=\'#\'>%s</a>',
                                 $row['nick'], $row['nick']);
                $line = $row['line'];
                //some magic to get rid of < and >
                $line = str_replace('<','&lt;',$line);
                $line = str_replace('>','&gt;',$line);
                //using some sort of bbcode
                for ($i = 0; $i < count($tags); $i++) {
                    $line = str_replace($tags[$i], $ntags[$i], $line);
                }
                //applying smiles
                for($i = 0; $i < $j; $i++) {
                    $line = str_replace($codes[$i], $image[$i], $line);
                }
                list($date, $time) = split(" ", $row['timestamp']);
                //returns a record to be shown by client
                echo $nick, ' [', $time, '] ', $line, '<br>';
            }
        }
    }

}
?>
